<template>
  <div class="main-content">
    <el-row :gutter="20" style="height: 100%;">
      <!-- 左侧部门树 -->
      <el-col :span="5" class="dept-tree-container">
        <el-card class="box-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon>
                  <OfficeBuilding/>
                </el-icon>
                <span>部门列表</span>
                <div class="header-tools">
                  <el-tooltip content="刷新部门" placement="top">
                    <el-icon class="tool-icon" @click="loadDeptTree">
                      <Refresh/>
                    </el-icon>
                  </el-tooltip>
                  <el-tooltip content="全部展开" placement="top">
                    <el-icon class="tool-icon" @click="expandAll">
                      <ArrowDown/>
                    </el-icon>
                  </el-tooltip>
                  <el-tooltip content="全部折叠" placement="top">
                    <el-icon class="tool-icon" @click="collapseAll">
                      <ArrowRight/>
                    </el-icon>
                  </el-tooltip>
                </div>
              </div>
              <el-input
                  v-model="deptName"
                  placeholder="输入部门名称"
                  clearable
                  style="margin-top: 8px"
                  @clear="loadDeptTree"
              >
                <template #prefix>
                  <el-icon>
                    <Search/>
                  </el-icon>
                </template>
              </el-input>
            </div>
          </template>
          <el-tree
              ref="deptTreeRef"
              :data="deptTreeData"
              :props="{ label: 'label', children: 'children' }"
              :default-expand-all="isExpand"
              :expanded-keys="expandedKeys"
              highlight-current
              node-key="id"
              :expand-on-click-node="false"
              @node-click="handleDeptNodeClick"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div class="node-icon">
                  <el-icon v-if="node.expanded && node.childNodes?.length">
                    <FolderOpened/>
                  </el-icon>
                  <el-icon v-else>
                    <Folder/>
                  </el-icon>
                </div>
                <span class="node-label">{{ node.label }}</span>
                <span class="node-count" v-if="deptCounts[data.id as number]">({{
                    deptCounts[data.id as number]
                  }})</span>
                <div class="node-actions">
                  <el-tooltip content="查看部门用户" placement="top">
                    <el-icon class="action-icon" @click.stop="handleDeptNodeClick(data)">
                      <View/>
                    </el-icon>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧用户列表 -->
      <el-col :span="19" class="user-list-container">
        <el-scrollbar>
          <AsyncSearchTable
              ref="userTableRef"
              @search="handleSearch"
              :columns="allColumns"
              :search-items="searchItems"
              :fetch-data="fetchUsers"
              @selection-change="handleSelectionChange"
          >
            <template #status="{ row }">
              <el-tag :type="row.status === '0' ? 'success' : row.status === '1' ? 'warning' : 'danger'">
                {{ row.status === '0' ? '正常' : row.status === '1' ? '停用' : '未知' }}
              </el-tag>
            </template>
            <template #toolbar>
              <el-button type="primary" :icon="Plus" @click="handleAdd">新增用户</el-button>
              <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
              <el-button type="warning" :icon="Download">导出</el-button>
            </template>
            <template #action-column="{row}">
              <el-button type="info" link :icon="View">查看</el-button>
              <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-popover
                  placement="bottom"
                  trigger="click"
                  :width="80"
              >
                <template #reference>
                  <el-button type="primary" link :icon="More">更多</el-button>
                </template>
                <div class="popover-actions">
                  <el-button
                      type="success"
                      link
                      :icon="Key"
                      @click="handleResetPwd(row)"
                  >
                    重置密码
                  </el-button>
                  <el-button
                      type="warning"
                      link
                      :icon="row.status === '0' ? Lock : Unlock"
                      @click="handleStatusChange(row)"
                  >
                    {{ row.status === '0' ? '停用' : '启用' }}
                  </el-button>
                  <el-button
                      type="danger"
                      link
                      :icon="Delete"
                      @click="handleDelete(row)"
                  >
                    删除
                  </el-button>
                </div>
              </el-popover>

            </template>
          </AsyncSearchTable>
        </el-scrollbar>

      </el-col>
    </el-row>

    <!-- 用户表单组件 -->
    <UserForm
        v-model:visible="userFormVisible"
        :type="userFormType"
        :user-data="currentUser"
        @success="handleUserFormSuccess"
    />

    <!-- 重置密码组件 -->
    <ResetPassword
        v-model:visible="resetPwdVisible"
        :user-data="currentUser"
        @success="handleResetPwdSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import AsyncSearchTable from '@/components/AsyncSearchTable/index.vue'
import * as http from "@/api/http.ts"
import {
  ArrowDown,
  ArrowRight,
  Delete,
  Download,
  Edit,
  Folder,
  FolderOpened,
  Key,
  Lock,
  More,
  OfficeBuilding,
  Plus,
  Refresh,
  Search,
  Unlock,
  View
} from "@element-plus/icons-vue"
import type {SearchItem} from "@/types/search.ts"
// 导入提取的组件
import UserForm from './userForm.vue'
import ResetPassword from './resetPassword.vue'

// 定义部门树节点的接口
interface DeptNode {
  id: number;
  label: string;
  children?: DeptNode[];
}

// 部门相关
const deptTreeRef = ref()
const deptName = ref('')
const selectedDeptId = ref<number | null>(null)
const isExpand = ref(true)
const expandedKeys = ref<number[]>([])
const deptCounts = reactive<Record<number, number>>({
  1: 18,  // 总公司有18个用户
  2: 8,   // 技术部有8个用户
  3: 6,   // 市场部有6个用户
  4: 2,   // 财务部有2个用户
  5: 3,   // 研发一组有3个用户
  6: 3,   // 研发二组有3个用户
  7: 2,   // 测试组有2个用户
  8: 3,   // 销售组有3个用户
  9: 3,   // 策划组有3个用户
  10: 2   // 行政部有2个用户
})
const handleSearch = (receivedParams: any) => {
  console.log('A组件接收到参数:', receivedParams);
}
const deptTreeData = ref<DeptNode[]>([
  {
    id: 1,
    label: '总公司',
    children: [
      {
        id: 2,
        label: '技术部',
        children: [
          {
            id: 5,
            label: '研发一组'
          },
          {
            id: 6,
            label: '研发二组'
          },
          {
            id: 7,
            label: '测试组'
          }
        ]
      },
      {
        id: 3,
        label: '市场部',
        children: [
          {
            id: 8,
            label: '销售组'
          },
          {
            id: 9,
            label: '策划组'
          }
        ]
      },
      {
        id: 4,
        label: '财务部'
      },
      {
        id: 10,
        label: '行政部'
      }
    ]
  }
])

// 用户表格引用
const userTableRef = ref()

// 表格列配置
const allColumns = [
  {prop: 'account', label: '账户', width: 120},
  {prop: 'name', label: '名字', width: 120},
  {prop: 'email', label: '邮箱', width: 200},
  {prop: 'age', label: '年龄', width: 120},
  {prop: 'gender', label: '性别', width: 120},
  {prop: 'status', label: '状态', width: 80},
  {prop: 'createdTime', label: '创建时间', width: 160},
  {prop: 'createdBy', label: '创建人', width: 100},
  {prop: 'updatedTime', label: '更新时间', width: 160},
  {prop: 'updatedBy', label: '更新人', width: 100}
]

// 获取用户列表数据
const fetchUsers = async (params: any) => {
  try {
    // 合并部门ID参数
    const requestParams = {...params}
    if (selectedDeptId.value) {
      requestParams.deptId = selectedDeptId.value
    }

    // 实际开发中替换为真实的API调用
    const response = await http.get('/api/users', {params: requestParams})
    console.log(response.data);
    return response.data
  } catch (error) {
    console.error('获取用户列表失败', error)
    return {
      rows: [],
      total: 0
    }
  }
}

// 状态选项
const statusOptions = [
  {label: '全部', value: ''},
  {label: '正常', value: '0'},
  {label: '停用', value: '1'}
]

// 部门选项转换为符合SearchItem要求的格式
const deptSelectOptions = [
  {label: '全部', value: ''},
  {label: '总公司', value: 1},
  {label: '技术部', value: 2},
  {label: '市场部', value: 3},
  {label: '财务部', value: 4},
  {label: '研发一组', value: 5},
  {label: '研发二组', value: 6},
  {label: '测试组', value: 7},
  {label: '销售组', value: 8},
  {label: '策划组', value: 9},
  {label: '行政部', value: 10}
]

// 搜索项配置
const searchItems: SearchItem[] = [
  {
    field: 'userName',
    label: '用户名称',
    type: 'input',
    placeholder: '请输入用户名称'
  },
  {
    field: 'status',
    label: '状态',
    type: 'select',
    options: statusOptions
  }
]

// 用户表单对话框相关
const userFormVisible = ref(false)
const userFormType = ref('add') // add, edit, view
const currentUser = ref({})

// 重置密码对话框相关
const resetPwdVisible = ref(false)

// 选中的行
const selectedRows = ref<any[]>([])

// 页面加载完成后执行
onMounted(() => {
  loadDeptTree()
  // 初始化展开所有节点
  if (isExpand.value) {
    expandAll()
  }
})

// 加载部门树
const loadDeptTree = () => {
  // 实际开发中这里应该调用API获取部门树数据
  // 示例：如果有部门名称搜索条件，则过滤部门树
  if (deptName.value) {
    // 简单过滤示例，实际开发中可能需要更复杂的递归过滤逻辑
    const filterTreeData = JSON.parse(JSON.stringify(deptTreeData.value))
    // 这里实现过滤逻辑
    // ...
  }
}

// 处理部门树节点点击
const handleDeptNodeClick = (data: any) => {
  selectedDeptId.value = data.id
  // 刷新用户列表，显示选中部门的用户
  refreshList()
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm('确定要删除选中的用户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际开发中会调用删除接口
    ElMessage.success('删除成功')
    // 刷新列表
    refreshList()
  }).catch(() => {
  })
}

// 新增用户
const handleAdd = () => {
  userFormType.value = 'add'
  currentUser.value = {
    // 如果选中了部门，将选中的部门ID设置为默认部门
    deptId: selectedDeptId.value || undefined
  }
  userFormVisible.value = true
}

// 查看用户
const handleView = (row: any) => {
  userFormType.value = 'view'
  currentUser.value = row
  userFormVisible.value = true
}

// 编辑用户
const handleEdit = (row: any) => {
  userFormType.value = 'edit'
  currentUser.value = row
  userFormVisible.value = true
}

// 删除用户
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除用户"${row.userName}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际开发中会调用删除接口
    ElMessage.success('删除成功')
    // 刷新列表
    refreshList()
  }).catch(() => {
  })
}

// 重置用户密码
const handleResetPwd = (row: any) => {
  currentUser.value = row
  resetPwdVisible.value = true
}

// 修改用户状态
const handleStatusChange = (row: any) => {
  const newStatus = row.status === '0' ? '1' : '0'
  const statusText = newStatus === '0' ? '启用' : '停用'

  ElMessageBox.confirm(`确认要${statusText}用户"${row.userName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际开发中会调用修改状态接口
    ElMessage.success(`${statusText}成功`)
    // 更新行数据
    row.status = newStatus
  }).catch(() => {
  })
}

// 用户表单提交成功处理
const handleUserFormSuccess = () => {
  refreshList()
}

// 密码重置成功处理
const handleResetPwdSuccess = () => {
  ElMessage.success('密码重置成功')
}

// 刷新列表
const refreshList = () => {
  // 调用表格组件的刷新方法
  userTableRef.value?.refresh?.()
}

// 全部展开
const expandAll = () => {
  isExpand.value = true
  // 递归获取所有节点ID
  const getAllKeys = (data: DeptNode[]): number[] => {
    let keys: number[] = []
    data.forEach(node => {
      keys.push(node.id)
      if (node.children && node.children.length > 0) {
        keys = keys.concat(getAllKeys(node.children))
      }
    })
    return keys
  }

  expandedKeys.value = getAllKeys(deptTreeData.value)
}

// 全部折叠
const collapseAll = () => {
  isExpand.value = false
  expandedKeys.value = []
}

// 切换展开/折叠
const toggleExpand = () => {
  isExpand.value = !isExpand.value
  isExpand.value ? expandAll() : collapseAll()
}
</script>

<style scoped>
.main-content {
  height: calc(100vh - 141px);
}

.dept-tree-container {
  height: 100%;
}

.user-list-container {
  height: 100%;
  overflow: auto;
}

.box-card {
  height: 100%;
  overflow: hidden;
  border-radius: 8px;
}

.card-header {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.header-title {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  position: relative;
}

.header-title span {
  font-size: 16px;
  font-weight: 600;
  margin-left: 8px;
}

.header-tools {
  position: absolute;
  right: 0;
  display: flex;
  align-items: center;
}

.tool-icon {
  margin-left: 8px;
  font-size: 16px;
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
}

.tool-icon:hover {
  color: #409eff;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 6px 0;
}

.node-icon {
  margin-right: 6px;
  color: #909399;
}

.node-label {
  flex: 1;
  font-size: 14px;
}

.node-count {
  margin-left: 4px;
  font-size: 12px;
  color: #909399;
}

.node-actions {
  margin-left: auto;
  opacity: 0;
  transition: opacity 0.3s;
}

.custom-tree-node:hover .node-actions {
  opacity: 1;
}

.action-icon {
  margin-left: 8px;
  font-size: 14px;
  cursor: pointer;
  color: #909399;
}

.action-icon:hover {
  color: #409eff;
}

/* 自定义滚动条样式 */
:deep(.el-card__body) {
  height: calc(100% - 100px);
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 6px;
  scrollbar-width: thin;
}

/* webkit浏览器的滚动条样式 */
:deep(.el-card__body)::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

:deep(.el-card__body)::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

:deep(.el-card__body)::-webkit-scrollbar-thumb:hover {
  background-color: #c0c4cc;
}

:deep(.el-card__body)::-webkit-scrollbar-track {
  background-color: #f5f7fa;
  border-radius: 3px;
}

/* 设置树组件的样式 */
:deep(.el-tree) {
  background: transparent;
}

:deep(.el-tree-node__content) {
  height: 36px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
}

.popover-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-start;

  .el-button:first-child {
    margin-left: 12px;
  }
}
</style>